-- UIBloodAltar
-- Created by chengb Nov/11/2015
-- 鲜血祭坛

require "game/ui/form/equips/UIEquipTooltip"
require "game/ui/form/equips/UIEquips"

UIBloodAltar = class("UIBloodAltar", function()
    return cc.Layer:create();
end);

function UIBloodAltar.create()
    return UIBloodAltar.new();
end

-- 材料图标缩放比例
local ITEM_ICON_SCALE = 0.6;

-- 构造函数
function UIBloodAltar:ctor()
    self:setName("UIBloodAltar");
    local node = cc.CSLoader:createNode("layout/dungeon/special/BloodAltar.csb");
    self:addChild(node);
    self.node = node;
    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 初始化
    self:init();

    -- 适配
    self:resize();
end

-- 适配
function UIBloodAltar:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 注册事件处理回调函数
function UIBloodAltar:registerEventCallback()
    -- 关注工坊放入装备的事件
    EventMgr.register("UIBloodAltar", event.BLACKSMITH_INPUT_EQUIP, function(args)
        local classId = args.classId;
        if not classId then
            return;
        end

        self.classId = classId;

        -- 重绘圣器信息
        self:redrawHolyItems();
    end);

    -- 关注圣器属性升级的事件
    EventMgr.register("UIBloodAltar", event.HOLY_ITEMS_IMPROVE, function(args)
        local classId = args.classId;
        local level   = args.level;
        local upgradeType = args.upgradeType;
        local isSucc  =  args.isSucc;

        if self.classId ~= classId then
            return;
        end

        local effectNode = findChildByName(self.node, "CT/target_node/effect_node");
        effectNode:removeAllChildren();

        if upgradeType == "base"  then
            if not isSucc then
                -- 升级失败了
                local upgradeCost = HolyItemsM.calcUpgradeBaseLevelCost();
                local materialId  = upgradeCost[2];
                local materialName = ItemM.query(materialId, "name");
                alert(string.format(getLocStr("holy_items_improve_falied"), materialName));
            else
                -- 基础属性提升
                local name = ItemM.query(classId, "name");
                local msg = string.format(getLocStr("holy_items_base_prop_improved"), name, level);
                alert(msg);
                playEffect(effectNode, 1277, 0, 0, nil, 0.83);
            end
        else
            if not isSucc then
                -- 升级失败了
                local upgradeCost = HolyItemsM.calcUpgradeExtraLevelCost();
                local materialId  = upgradeCost[2];
                local materialName = ItemM.query(materialId, "name");
                alert(string.format(getLocStr("holy_items_improve_falied"), materialName));
            else
                -- 特殊属性提升
                local name = ItemM.query(classId, "name");
                local msg = string.format(getLocStr("holy_items_special_prop_improved"), name, level);
                alert(msg);
                playEffect(effectNode, 1277, 0, 0, nil, 0.83);
            end
        end

        -- 刷新界面
        self:redrawHolyItems();
    end);

    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            cclog("UIBloodAltar 界面析构清理");

            -- 移除所有事件关注
            EventMgr.removeAll("UIBloodAltar");

            if UIDungeonMgr:getCurLevel() then
                UIDungeonMgr:getCurLevel():showMenu();
            end

        elseif eventType == "enter" then
            if UIDungeonMgr:getCurLevel() then
                UIDungeonMgr:getCurLevel():hideMenu();
            end
        end
    end);
end

-- 注册点击事件
function UIBloodAltar:registerTouchEvent()
    -- 注册返回按钮点击事件
    local node = self.node;
    local btnBack = findChildByName(node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");
            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UIBloodAltar");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册提升基础属性按钮点击事件
    local btnBase  = findChildByName(self.node, "CT/btn_base");
    local function onBaseClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            if not self.classId then
                return;
            end

            -- 尝试提升属性
            self:tryUpgradeBaselevel(self.classId);
        end
    end
    btnBase:addTouchEventListener(onBaseClick);

    -- 注册提升特殊属性按钮点击事件
    local btnExtra = findChildByName(self.node, "CT/btn_extra");
    local function onExtraClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            if not self.classId then
                return;
            end

            -- 尝试提升特殊属性
            self:tryUpgradeExtralevel(self.classId);
        end
    end
    btnExtra:addTouchEventListener(onExtraClick);

    -- 注册格子点击事件
    local frameImg = findChildByName(self.node, "CT/target_node/frame");
    local function onFrameClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 打开包裹界面
            local uiEquip = UIEquips.create(EQUIP_OPEN_TYPE_HOLY_ITEMS, {["holy_type"] = "holy"});
            UIMgr.getCurrentScene():addForm(uiEquip);
        end
    end
    frameImg:addTouchEventListener(onFrameClick);
end

-- 尝试提升基础属性
function UIBloodAltar:tryUpgradeBaselevel(classId)
    -- 执行提升
    DungeonActionM.go("holy_items_base_improve", 0, classId);
end

-- 尝试提升特殊属性
function UIBloodAltar:tryUpgradeExtralevel(classId)
    -- 获取当前特殊属性的等级
    local curLevel = HolyItemsM.getExtraLevel(classId);

    -- 判断基础属性等级是否达标
    local requireBaseLevel = FormulaM.invoke("CALC_HOLY_ITEMS_BASE_LEVEL_REQUIRE", classId, curLevel);
    local curBaseLevel = HolyItemsM.getBaseLevel(classId);
    if curBaseLevel < requireBaseLevel then
        local msg = string.format(getLocStr("fail_to_upgrade_specail_prop"), requireBaseLevel);
        alert(msg);
        return;
    end

    -- 执行提升
    DungeonActionM.go("holy_items_extra_improve", 0, classId);
end

-- 初始化窗口
function UIBloodAltar:init()
    -- 标题
    local titleLabel = findChildByName(self.node, "CT/title_node/title");
    titleLabel:setString(getLocStr("blood_altar"));
    TextStyleM.setArtWordTitleStyle(titleLabel);

    local kerning, kerning2 = 0, 0;
    if getLang() ~= "zh" and getLang() ~= "tw" then
        kerning, kerning2 = -3, -1;
    end

    -- 描述
    local descLabel  = findChildByName(self.node, "CT/desc");
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN, false, kerning2);
    applyString(descLabel, getLocStr("blood_altar_desc"));

    -- 隐藏圣器图标
    local equipImg = findChildByName(self.node, "CT/target_node/icon");
    self.equipImg = equipImg;
    checkAddBubbleStatus(self.equipImg);
    -- equipImg:setVisible(false);
    local frame = findChildByName(self.node, "CT/target_node/frame");

    -- 初始化消耗
    self:initUpgradeBaseCost();
    self:initUpgradeSpecialCost();
end

-- 初始化基础消耗显示
function UIBloodAltar:initUpgradeBaseCost()
    local itemNode = findChildByName(self.node, "CT/item_node");
    local priceLabel = findChildByName(itemNode, "amount");
    local upgradeCost = HolyItemsM.calcUpgradeBaseLevelCost();
    local itemId  = upgradeCost[2];
    local curAmount = ItemM.getAmount(ME.user, itemId);
    TextStyleM.setTextStyle(priceLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE);

    -- 显示当前数量
    priceLabel:setString(curAmount .. "/" .. getLocStr("default_value_text2"));

    local iconImg = findChildByName(itemNode, "icon");
    local icon = ItemM.query(itemId, "icon");
    iconImg:loadTexture(getItemIconPath(icon));
    iconImg:setScale(ITEM_ICON_SCALE);

    -- 提升按钮置灰
    local btnBase = findChildByName(self.node, "CT/btn_base");
    self.btnBase = btnBase;
    TextStyleM.setTextStyle(btnBase, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    setButtonEnabled(btnBase, false);
    self.btnBase:setTitleText(getLocStr("improve_base_prop"));
    local iconImg = findChildByName(self.btnBase, "icon");
    iconImg:loadTexture(getItemIconPath(icon));
    iconImg:setScale(ITEM_ICON_SCALE);
end

-- 初始化特殊消耗显示
function UIBloodAltar:initUpgradeSpecialCost()
    local itemNode = findChildByName(self.node, "CT/item2_node");
    local priceLabel = findChildByName(itemNode, "amount");
    local upgradeCost = HolyItemsM.calcUpgradeExtraLevelCost();
    local itemId  = upgradeCost[2];
    local curAmount = ItemM.getAmount(ME.user, itemId);
    TextStyleM.setTextStyle(priceLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE);
    priceLabel:setString(curAmount .. "/" .. getLocStr("default_value_text2"));

    local iconImg = findChildByName(itemNode, "icon");
    local icon = ItemM.query(itemId, "icon");
    iconImg:loadTexture(getItemIconPath(icon));
    iconImg:setScale(ITEM_ICON_SCALE);

    -- 提升按钮置灰
    local btnExtra = findChildByName(self.node, "CT/btn_extra");
    self.btnExtra = btnExtra;
    TextStyleM.setTextStyle(btnExtra, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    setButtonEnabled(btnExtra, false);
    self.btnExtra:setTitleText(getLocStr("improve_special_prop"));
    local iconImg = findChildByName(self.btnBase, "icon");
    iconImg = findChildByName(self.btnExtra, "icon");
    iconImg:loadTexture(getItemIconPath(icon));
    iconImg:setScale(ITEM_ICON_SCALE);
end

-- 显示提升基础属性消耗
function UIBloodAltar:redrawUpgradeBaseCost()
    local itemNode  = findChildByName(self.node, "CT/item_node");
    local upgradeCost = self.baseUpgradeCost;
    local itemId  = upgradeCost[2];
    local amount  = upgradeCost[3];
    local curAmount = ItemM.getAmount(ME.user, itemId);

    local priceLabel = findChildByName(itemNode, "amount");

    -- 消耗不足时，红色显示
    local isEnough = ItemM.getAmount(ME.user, itemId) >= amount;
    if not isEnough then
        TextStyleM.setTextStyle(priceLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_DARK_RED);
    else
        TextStyleM.setTextStyle(priceLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE);
    end

    local isMaxLevel = HolyItemsM.isBaseLevelMax(self.classId);
    if isMaxLevel then
        -- 等级已达上限
        priceLabel:setString(curAmount .. "/" .. getLocStr("default_value_text2"));
    else
        priceLabel:setString(curAmount .. "/" .. amount);
    end

    local iconImg = findChildByName(itemNode, "icon");
    local icon = ItemM.query(itemId, "icon");
    iconImg:loadTexture(getItemIconPath(icon));
    iconImg:setScale(ITEM_ICON_SCALE);

    -- 获取当前基础属性的等级
    local curLevel = HolyItemsM.getBaseLevel(self.classId);

    if isMaxLevel then
        -- 基础属性等级已达上限
        setButtonEnabled(self.btnBase, false);
        self.btnBase:setTitleText(getLocStr("max_level_yet"));
    elseif not isEnough then
        -- 消耗不足
        setButtonEnabled(self.btnBase, false);
        self.btnBase:setTitleText(getLocStr("improve_base_prop") .. "+" .. curLevel + 1);
    else
        -- 升级按钮亮起来
        setButtonEnabled(self.btnBase, true);
        self.btnBase:setTitleText(getLocStr("improve_base_prop") .. "+" ..curLevel + 1);
    end
end

-- 显示提升特殊属性消耗
function UIBloodAltar:redrawUpgradeExtraCost()
    local itemNode = findChildByName(self.node, "CT/item2_node");

    local upgradeCost = self.extraUpgradeCost;
    local itemId  = upgradeCost[2];
    local amount  = upgradeCost[3];
    local curAmount = ItemM.getAmount(ME.user, itemId);

    -- 消耗不足时，红色显示
    local priceLabel = findChildByName(itemNode, "amount");
    local isEnough = ItemM.getAmount(ME.user, itemId) >= amount;
    if not isEnough then
        TextStyleM.setTextStyle(priceLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_DARK_RED);
    else
        TextStyleM.setTextStyle(priceLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE);
    end

    local isMaxLevel = HolyItemsM.isExtraLevelMax(self.classId);
    if isMaxLevel then
        priceLabel:setString(curAmount .. "/" .. getLocStr("default_value_text2"));
    else
        priceLabel:setString(curAmount .. "/" .. amount);
    end

    local iconImg = findChildByName(itemNode, "icon");
    local icon = ItemM.query(itemId, "icon");
    iconImg:loadTexture(getItemIconPath(icon));
    iconImg:setScale(ITEM_ICON_SCALE);

    -- 获取当前特殊属性的等级
    local curLevel = HolyItemsM.getExtraLevel(self.classId);

    if isMaxLevel then
        -- 特殊属性等级已达上限
        setButtonEnabled(self.btnExtra, false);
        self.btnExtra:setTitleText(getLocStr("max_level_yet"));
    elseif not isEnough then
        -- 消耗不足
        setButtonEnabled(self.btnExtra, false);
        self.btnExtra:setTitleText(getLocStr("improve_special_prop") .. "+" ..  curLevel + 1);
    else
        -- 升级按钮亮起来
        setButtonEnabled(self.btnExtra, true);
        self.btnExtra:setTitleText(getLocStr("improve_special_prop")  .. "+" .. curLevel + 1);
    end
end

-- 重绘圣器信息
function UIBloodAltar:redrawHolyItems()
    -- 计算升级附加属性的消耗
    local baseUpgradeCost = HolyItemsM.calcUpgradeBaseLevelCost(self.classId);
    self.baseUpgradeCost = baseUpgradeCost;

    -- 计算升级基础属性的消耗
    local extraUpgradeCost = HolyItemsM.calcUpgradeExtraLevelCost(self.classId);
    self.extraUpgradeCost = extraUpgradeCost;

    -- 显示圣器图标
    local frame = findChildByName(self.node, "CT/target_node/frame");
    frame:removeAllChildren();

    local icon = ItemM.query(self.classId, "icon");
    self.equipImg:setVisible(true);
    self.equipImg:loadTexture(getItemIconPath(icon));


    -- 显示消耗
    self:redrawUpgradeBaseCost();
    self:redrawUpgradeExtraCost();

    -- 显示按钮上的小图标
    local itemId = self.baseUpgradeCost[2];
    local icon = ItemM.query(itemId, "icon");
    local iconImg = findChildByName(self.btnBase, "icon");
    iconImg:loadTexture(getItemIconPath(icon));
    iconImg:setScale(ITEM_ICON_SCALE);

    itemId = self.extraUpgradeCost[2];
    icon = ItemM.query(itemId, "icon");
    iconImg = findChildByName(self.btnExtra, "icon");
    iconImg:loadTexture(getItemIconPath(icon));
    iconImg:setScale(ITEM_ICON_SCALE);
end


